<template>
  <div class="dashboard-container" style="width: 100%;padding:0;margin:0;">
    <!-- 顶部标题栏 -->
    <el-row class="header-row">
      <el-col :span="24" class="header-content">
        <h1>目标管理</h1>
        <div class="header-info">
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="15" class="chart-row" style="margin-top: 1rem">

      <el-col :span="24" class="chart-card" style="height: 500px">

        <el-card :body-style="{ padding: '15px' }">
          <div slot="header" class="chart-header">
            <span><i class="fa fa-table"></i> 目标明细</span>
            <el-button
                type="primary"
                @click="goal_add_dialog_visible = true"
            >
              新增目标
            </el-button>
            <DashBoardComponent />
          </div>
          <!-- 表格 -->
          <div>
            <el-table
                height="350"
                border
                :data="goal_data"
                style="width: 100%"
                class="ml-5"
            >
              <el-table-column
                  prop="id"
                  label="目标id"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="first_cate_name"
                  align="center"
                  label="目标一级分类">
              </el-table-column>
              <el-table-column
                  prop="goal_name"
                  align="center"
                  label="目标名称">
              </el-table-column>
              <el-table-column
                  prop="start_date"
                  label="目标开始时间"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="end_date"
                  label="目标完成时间"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="focus_time"
                  align="center"
                  label="专注时间(小时)"
                  sortable
              >
              </el-table-column>
              <el-table-column
                  prop="todo_num"
                  align="center"
                  label="完成任务数"
                  sortable
              >
              </el-table-column>
              <el-table-column
                  prop="goal_status"
                  align="center"
                  label="目标状态">
                <!-- 直接在 template 中通过条件判断转换状态 -->
                <template slot-scope="scope">
                  <el-tag type="info" v-if="scope.row.goal_status === 0">未完成</el-tag>
                  <el-tag type="success" v-else-if="scope.row.goal_status === 1">完成</el-tag>
                  <el-tag type="warning" v-else-if="scope.row.goal_status === 2">暂缓</el-tag>
                  <el-tag type="error" v-else style="color: #999;">未知状态</el-tag> <!-- 异常状态兜底 -->
                </template>
              </el-table-column>
              <el-table-column
                  prop="execute"
                  label="操作"
                  align="center">
                <template #default="scope">
                  <!-- 编辑按钮，使用编辑图标 -->
                  <el-button
                      size="small"
                      type="primary"
                      icon="el-icon-edit"
                      @click="handleEdit(scope.row)">
                  </el-button>
                  <!-- 删除按钮，使用删除图标 -->
                  <el-popconfirm
                      style="margin-left: 1rem"
                      confirm-button-text='确定'
                      cancel-button-text='取消'
                      icon="el-icon-info"
                      icon-color="red"
                      title="确定删除此分配方案吗？"
                      @confirm="handleDelete(scope.row.id)"
                  >
                    <el-button
                        size="small"
                        type="danger"
                        icon="el-icon-delete"
                        slot="reference"
                    >
                    </el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                  @size-change="size_change"
                  @current-change="current_change"
                  :current-page="ExpCurrentPage"
                  :page-sizes="[5, 20, 30, 40]"
                  :page-size="ExpPageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="ExpTotalCount"
              ></el-pagination>
            </div>

          </div>

        </el-card>
        <el-dialog title="新增目标" :visible.sync="goal_add_dialog_visible">
          <el-form :model="add_goal_form" @keyup.enter.native="add_goal">
            <el-form-item label="目标开始日期" :label-width="formLabelWidth">
              <el-date-picker
                  type="date"
                  value-format="yyyy-MM-dd"
                  v-model="add_goal_form.start_date"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="目标完成日期" :label-width="formLabelWidth">
              <el-date-picker
                  type="date"
                  value-format="yyyy-MM-dd"
                  v-model="add_goal_form.end_date"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="目标一级分类" :label-width="formLabelWidth">
              <el-select
                  v-model="add_goal_form.first_cate_id"
                  placeholder="目标一级分类"
                  filterable
              >
                <el-option v-for="item in goal_first_cate_list" :key="item.id" :label="item.first_cate_name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目标名称" :label-width="formLabelWidth">
              <el-input placeholder="请输入目标名称" v-model="add_goal_form.goal_name"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="goal_add_dialog_visible = false">取 消</el-button>
            <el-button type="primary" @click="add_goal">确 定</el-button>
          </div>
        </el-dialog>
        <!--编辑模态框。-->
        <el-dialog title="编辑目标" :visible.sync="edit_goal_dialog_visible">
          <el-form :model="edit_goal_form" @keyup.enter.native="edit_goal">
            <el-form-item label="目标ID" :label-width="formLabelWidth">
              <el-input v-model="edit_goal_form.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="开始日期" :label-width="formLabelWidth">
              <el-date-picker
                  type="date"
                  value-format="yyyy-MM-dd"
                  v-model="edit_goal_form.start_date"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期" :label-width="formLabelWidth">
              <el-date-picker
                  type="date"
                  value-format="yyyy-MM-dd"
                  v-model="edit_goal_form.end_date"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="目标一级分类" :label-width="formLabelWidth">
              <el-select
                  v-model="edit_goal_form.first_cate_id"
                  placeholder="目标一级分类"
                  filterable
              >
                <el-option v-for="item in goal_first_cate_list" :key="item.id" :label="item.first_cate_name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目标名称" :label-width="formLabelWidth">
              <el-input placeholder="请修改目标名称" v-model="edit_goal_form.goal_name"></el-input>
            </el-form-item>
            <el-form-item label="目标状态" :label-width="formLabelWidth">
              <el-select
                  v-model="edit_goal_form.goal_status"
                  placeholder="目标状态"
                  filterable
              >
                <el-option v-for="item in goal_status_list" :key="item.id" :label="item.goal_status"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="edit_goal_dialog_visible = false">取 消</el-button>
            <el-button type="primary" @click="edit_goal">确 定</el-button>
          </div>
        </el-dialog>

      </el-col>
    </el-row>
  </div>
</template>

<script>
// import axios from 'axios'

import moment from 'moment';

export default {
  components: {
  },

  computed: {},

  name: 'GoalView',

  data() {

    return {
      goal_status_list: [
        {
          id: '0',
          goal_status: '未完成',
        },
        {
          id: '1',
          goal_status: '已完成',
        },
        {
          id: '2',
          goal_status: '暂缓',
        },
      ]
      ,

      // 表格当前页显示的数据
      goal_data: [],
      // 当前页码
      ExpCurrentPage: 1,
      // 每页显示条数
      ExpPageSize: 5,
      // 总数据条数
      ExpTotalCount: 0,

      // 支出指标卡数据
      ExpenseCardList: [
        {name: "当年累计支出", value: "100万"},
        {name: "当月累计支出", value: "12万"},
      ],
      // 当日目标
      all_goal: [],
      // 支出时间选择
      exp_date: moment(new Date()).format('YYYY-MM-DD'),
      // 新增支出弹窗表单组件配置项
      goal_add_dialog_visible: false,

      // 新增目标表单
      add_goal_form: {
        first_cate_id: null, // 目标一级分类
        goal_name: null,//目标名称
        start_date: moment(new Date()).format('YYYY-MM-DD'), // 目标设定日期
        end_date: '',// 计划完成日期
        goal_status: 0,
      },
      formLabelWidth: '120px',
      // 编辑支出表单模态框
      edit_goal_dialog_visible: false,
      // 编辑目标表单
      edit_goal_form: {
        id: null,
        first_cate_id: null, // 目标一级分类
        goal_name: null,//目标名称
        start_date: '', // 目标设定日期
        end_date: '',// 计划完成日期
        goal_status: 0,
      },

      // 所有一级分类列表
      goal_first_cate_list: [],
      // 基于一级分类筛选的可选的二级分类
      exp_second_cate_options: [],


    }
  },
  created() {
  },
  mounted() {
    this.call_daily_goal_data()
    this.call_goal_all_first_cate()
  },
  beforeDestroy() {
  },
  methods: {
    // 格式化数据
    formatData(value) {
      // 处理超过万的数值，保留两位小数并显示为“x.xx万”
      if (value >= 10000) {
        return (value / 10000).toFixed(2) + '万';
      } else if (value > 1) {
        return value.toFixed(2)
      }
      // 处理小数（这里假设小于1的数值是比例值，需要转成百分比）
      else if (value > 0 && value < 1) {
        return (value * 100).toFixed(2) + '%';
      }
      // 其他情况（如整数、不符合上述条件的小数等），直接返回原值
      else {
        return value
      }
    },

    // 支出卡片累计数据
    call_exp_card_data() {

      // 然后用这个instance发送请求
      this.$axios.post('/exp/statistics', {
        year: this.exp_date,
        month: this.exp_date,
        user_id: 1
      })
          .then(response => {
            this.ExpenseCardList = response.data.data.map(item => ({
              ...item,
              value: this.formatData(item.value)
            }))
          })
    },

    // 获取所有目标
    call_daily_goal_data() {
      // 然后用这个instance发送请求
      this.$axios.post('/goal/get_goals_details', {
      })
          .then(response => {
            this.all_goal = response.data.data.items.map(item => ({
              ...item,
              goal_status: Number(item.goal_status)
            }))
            this.pg_change()
            this.ExpTotalCount = this.all_goal.length

          })
          .catch(error => {
            console.error(error);
          });
    },


    // 处理每页条数变化
    size_change(val) {
      this.ExpPageSize = val;
      // 重置为第一页
      this.ExpCurrentPage = 1;
      this.pg_change();
    },

    // 处理页码变化
    current_change(val) {
      this.ExpCurrentPage = val;
      this.pg_change();
    },

    // 处理分页逻辑
    pg_change() {
      // 计算起始索引
      const startIndex = (this.ExpCurrentPage - 1) * this.ExpPageSize;
      // 计算结束索引
      const endIndex = startIndex + this.ExpPageSize;
      // 截取数据，实现前端分页
      this.goal_data = this.all_goal.slice(startIndex, endIndex);
    },

    // 获取所有的目标一级分类
    call_goal_all_first_cate() {
      this.$axios.get('/goal/get_goal_cate_by_user_id')
          .then(response => {
            if (response.data.code === 200) {
              this.goal_first_cate_list = response.data.data.map(item => ({
                ...item,
              }))
            } else {
              this.$message.error(response.data.message)
            }

          })
    },


    //打开编辑界面
    handleEdit(row) {
      this.edit_goal_dialog_visible = true;
      this.edit_goal_form = row
    },

    // 提交编辑表单。
    async edit_goal() {
      try {
        const res = await this.$axios.post('/goal/update_goal', this.edit_goal_form);
        if (res.data.code === 200) {
          this.$message.success('变更成功')
          this.call_daily_goal_data()

        } else if (res.data.code === 400) {
          this.$message({
            type: 'error',
            message: '更新失败' + res.data.message
          });
        }
      } catch (error) {
        // 可以在这里处理请求失败的情况（例如网络错误、后端返回错误等）
        console.error('更新失败：', error);
        this.$message({
          type: 'error',
          message: '更新失败，请重试。'
        });
      }
    },

    // 根据id删除
    handleDelete(id) {
      this.$axios.post('/goal/delete_goal', {
        id: id
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success('删除成功')
          this.call_daily_goal_data()
        } else if (res.data.code === 400) {
          this.$message.error(res.data.message)
        }
      })
    },
    // 新增目标
    add_goal() {
      this.$axios.post('/goal/add_goal', this.add_goal_form)
          .then(response => {
            if (response.data.code === 200) {
              this.$notify({
                type: 'success',
                title: '新增成功',
                message: '本次提交已完成。'
              })
              this.call_daily_goal_data()
            } else {
              this.$message.error(response.data.message)
            }
          })
    },


  },
  watch: {
    exp_date: {
      deep: true,
      immediate: true,
      handler() {
        this.call_daily_goal_data()
        this.call_exp_card_data()
        this.call_exp_struct_data()
        this.call_month_exp_data()
      }
    },
  }


}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.header-row {
  margin-bottom: 20px;
}

.header-content {
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.update-time {
  color: #666;
  font-size: 14px;
}

.kpi-row {
  margin-bottom: 20px;
}

.kpi-card {
  height: 100%;
}

.kpi-card .el-card {
  height: 100%;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.kpi-card .el-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.kpi-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.kpi-value {
  font-size: 22px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.kpi-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.kpi-trend.up {
  color: #e74c3c;

}

.kpi-trend.down {
  color: #42b983;

}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 100%;
}

.chart-card .el-card {
  height: 100%;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #333;
}

.chart-container {
  width: 100%;
  height: calc(100% - 44px);
  min-height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .kpi-card {
    flex: 0 0 33.333333%;
    max-width: 33.333333%;
  }

  .chart-card {
    flex: 0 0 50%;
    max-width: 50%;
  }
}

@media (max-width: 768px) {
  .kpi-card {
    flex: 0 0 50%;
    max-width: 50%;
  }

  .chart-card {
    flex: 0 0 100%;
    max-width: 100%;
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-info {
    width: 100%;
    justify-content: space-between;
  }
}

@media (max-width: 480px) {
  .kpi-card {
    flex: 0 0 100%;
    max-width: 100%;
  }
}

.is-selected {
  color: #1989FA;
}
</style>

<style scoped>
.table-pagination-container {
  padding: 20px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}
</style>
